<template>
  <div class="home-container">
    <!-- 顶部导航栏 -->
    <header class="top-nav">
      <div class="nav-left">
        <!-- <h1 class="logo">数智品诉定标平台</h1> -->
      </div>
      <div class="nav-center">
        <el-menu mode="horizontal" :default-active="activeTab" menu-trigger="click" @select="handleTabSelect"
          background-color="#002343" text-color="#fff" active-text-color="#fff" :unique-opened="true"
          style="border-bottom: none; height: 70px; background-color: transparent;">
          <!-- 使用计算属性获取没有子菜单的菜单项 -->
          <el-menu-item v-for="menu in simpleMenus" :key="menu.index" :index="menu.index">
            {{ menu.label }}
          </el-menu-item>

          <!-- 使用计算属性获取有子菜单的菜单项 -->
          <el-submenu v-for="menu in subMenus" :key="menu.index" :index="menu.index">
            <template slot="title">{{ menu.label }}</template>
            <el-menu-item v-for="child in menu.children" :key="child.index" :index="child.index">
              {{ child.label }}
            </el-menu-item>
          </el-submenu>
        </el-menu>
      </div>
      <div class="nav-right">
        <el-dropdown @command="handleDropdownCommand">
          <span class="user-info">
            <i class="el-icon-s-custom"></i>
            {{ username }} ({{ userRoleText }})
            <i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </header>

    <!-- 主内容区域 -->
    <main class="main-content">
      <router-view></router-view>
    </main>
  </div>
</template>

<script>
// 导入Element UI原生的Message组件
import { Message } from 'element-ui';

export default {
  name: 'Home',
  data() {
    return {
      username: localStorage.getItem('username') || '管理员',
      userRole: localStorage.getItem('DzRoles') || 'guest',
      menuItems: [],
      currentActiveTab: 'dashboard'
    }
  },
  computed: {
    activeTab() {
      // 获取当前路由的最后一部分作为激活的标签
      const path = this.$route.path.split('/').pop()
      // 特殊处理：将systemSettings映射为settings
      if (path === 'systemSettings') {
        return 'settings'
      }
      return path || 'dashboard'
    },
    userRoleText() {
      // 角色文本映射
      const roleMap = {
        'guest': '用户',
        'enterprise': '企业',
        'admin': '管理员'
      }
      return roleMap[this.userRole] || this.userRole
    },
    // 计算属性：获取没有子菜单的菜单项
    simpleMenus() {
      return this.menuItems.filter(menu => !menu.children || menu.children.length === 0)
    },
    // 计算属性：获取有子菜单的菜单项
    subMenus() {
      return this.menuItems.filter(menu => menu.children && menu.children.length > 0)
    }
  },
  created() {
    this.generateMenuByRole()
  },
  methods: {
    // 根据用户角色生成菜单
    // 根据用户角色生成菜单
    generateMenuByRole() {
      const role = this.userRole
      let menuItems = []



      // 只有admin能看到首页
      if (role === 'admin') {
        menuItems.push({
          index: 'dashboard',
          label: '首页',
          children: []
        })
      }

      // 标准相关菜单（所有角色都可访问）
      const standardMenu = {
        index: 'users',
        label: '标准',
        children: [
          { index: 'userManagement', label: '国家标准' },
          { index: 'userProfile', label: '行业标准' }
        ]
      }
      menuItems.push(standardMenu)

      // 产品相关菜单（所有角色都可访问）
      const productMenu = {
        index: 'pro',
        label: '产品',
        children: [
          { index: 'queryPro', label: '产品查询' },
          { index: 'comparePro', label: '产品对比' }
        ]
      }

      // 企业角色和管理员可以看到企业信息
      if (role === 'enterprise' || role === 'admin' || role === 'guest') {
        productMenu.children.push({ index: 'enterprise', label: '企业信息' })
      }

      menuItems.push(productMenu)

      // 投诉相关菜单（所有角色都可访问）- 移到条件判断外
      const complaintMenu = {
        index: 'complaint',
        label: '投诉',
        children: [
          { index: 'settings', label: '产品投诉' },
          { index: 'complaint', label: '企业投诉' }
        ]
      }


      // 数据管理菜单（仅企业和管理员可见）
      if (role === 'enterprise' || role === 'admin') {
        const dataMenu = {
          index: 'datacom',
          label: '数据管理',
          children: []
        }

        // 仅管理员可以采集数据
        if (role === 'admin' || role === 'enterprise') {
          dataMenu.children.push({ index: 'collect', label: '数据采集' })
          dataMenu.children.push({ index: 'queryCollect', label: '数据查询' })

        }

        // 企业和管理员都可以查询数据

        menuItems.push(dataMenu)
      }

      this.menuItems = menuItems
      menuItems.push(complaintMenu)

    },

    handleTabSelect(tabIndex) {
      // 保存当前激活的tab索引
      this.currentActiveTab = tabIndex

      // 根据选择的标签切换路由 - 使用正确的子路由路径
      let routePath = ''
      switch (tabIndex) {
        case 'dashboard':
          routePath = '/dashboard'
          break
        case 'userManagement':
          routePath = '/userManagement'
          break
        case 'userProfile':
          routePath = '/userProfile'
          break
        case 'settings':
          routePath = '/systemSettings'
          break
        case 'queryPro':
          routePath = '/queryPro'
          break
        case 'comparePro':
          routePath = '/comparePro'
          break
        case 'enterprise':
          routePath = '/enterprise'
          break
        case 'collect':
          routePath = '/collect'
          break
        case 'queryCollect':
          routePath = '/queryCollect'
          break
        case 'complaint':
          routePath = '/complaint'
          break
        default:
          routePath = '/dashboard'
      }

      // 关键修改：检查目标路由是否与当前路由相同，不同时才执行push
      if (this.$route.path !== routePath) {
        this.$router.push(routePath)
      }
    },
    handleLogout() {
      // 退出登录逻辑 - 使用原生Message组件
      localStorage.removeItem('token')
      localStorage.removeItem('username')
      localStorage.removeItem('DzRoles') // 清除角色信息

      // 先移除token再显示消息，避免消息被拦截
      setTimeout(() => {
        Message.success('退出登录成功')
      }, 100)

      // 强制路由跳转
      this.$router.replace('/login')
    },
    // 新增：处理下拉菜单命令
    handleDropdownCommand(command) {
      if (command === 'logout') {
        this.handleLogout()
      }
    }
  },
  mounted() {
    // 检查token是否存在
    const token = localStorage.getItem('token')
    if (!token) {
      this.$router.push('/login')
      return
    }

    // 根据用户角色进行不同的重定向
    const userRole = localStorage.getItem('DzRoles')
    if (userRole === 'guest') {
      // 修改为只在根路径时才重定向
      if (this.$route.path === '/') {
        this.$router.push('/userManagement')
      }
    } else if (userRole === 'admin') {
      // admin用户重定向到dashboard
      if (this.$route.path === '/') {
        this.$router.push('/dashboard')
      }
    } else if (userRole === 'enterprise') {
      // 修改为只在根路径时才重定向
      if (this.$route.path === '/') {
        this.$router.push('/userManagement')
      }
    }
  },
  // 添加监听路由变化的方法，确保刷新页面后也能正确显示激活状态
  watch: {
    '$route'() {
      // 路由变化时，重新设置当前激活的tab
      const path = this.$route.path.split('/').pop()
      if (path === 'systemSettings') {
        this.currentActiveTab = 'settings'
      } else {
        this.currentActiveTab = path || 'dashboard'
      }
    },
    // 监听角色变化，重新生成菜单
    userRole() {
      this.generateMenuByRole()
    }
  }
}
</script>

<style scoped>




.home-container {
  height: 100vh;
  width: 100%;
  display: flex;
  flex-direction: column;
}

.main-content {
  flex: 1;
  width: 100%;
}

:deep(.el-menu--horizontal > .el-menu-item:hover),
:deep(.el-menu--horizontal > .el-submenu:hover > .el-submenu__title) {
  background-color: transparent !important;
  color: #fff !important;
}

:deep(.el-menu--horizontal > .el-menu-item),
:deep(.el-menu--horizontal > .el-submenu > .el-submenu__title) {
  color: #fff !important;
}



:deep(.el-menu--horizontal > .el-menu-item.is-active) {
  border-bottom: none !important;
  color: #fff !important;
}

:deep(.el-menu--horizontal > .el-submenu.is-active .el-submenu__title) {
  border-bottom: none !important;
  color: #fff !important;
}


/* 新增：调整用户管理下拉菜单中子菜单项的宽度 */
:deep(.el-submenu__dropdown .el-menu-item) {
  width: 50px !important;
  /* 将宽度设置为比默认更小的值 */
}

.top-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 70px;
  background-image: url('../assets/img/home/topnavbgc.png');
  background-color: #152133;
  
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 0 20px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.logo {
  font-size: 20px;
  color: #fff;
  margin: 0;
}

.nav-center {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.user-info {
  cursor: pointer;
  display: flex;
  align-items: center;
  color: #fff;
  font-size: 16px;
}

.user-info .el-icon-user {
  margin-right: 5px;
}

.main-content {
  flex: 1;
  padding-top: 60px;
  padding: 10px;
  padding-top: 80px;
  overflow-y: auto;
  background-color: #152133;

}

:deep(.el-menu--horizontal .el-submenu .el-submenu__dropdown) {
  background-color: #fff !important;
  border: none;
  width: 50px !important;
}

/* 确保下拉菜单项文字为白色 */
:deep .el-menu--horizontal .el-submenu .el-menu-item {
  color: #333;
  width: 50px !important;
}

/* 鼠标悬停时的样式 */
:deep .el-menu--horizontal .el-submenu .el-menu-item:hover {
  background-color: #f5f5f5 !important;
}

:deep .el-menu--horizontal .el-menu--popup-bottom-start {
  margin-top: 0px !important;
}





/* 为导航栏菜单项添加边框和倾斜效果 */
:deep(.el-menu--horizontal > .el-menu-item) {
  box-sizing: border-box;

  position: relative;
  border: 1px solid #2CDFE8;
  border-radius: 4px;
  transform: skew(-20deg);
  transition: all 0.3s ease;
  background-color: transparent;
  overflow: hidden;
  margin: 0 3px;
  /* 适当的间距 */
  padding: 0 10px !important;
  /* 合适的内边距 */
  font-size: 14px !important;
  /* 适中的字号 */
  height: 32px !important;
  /* 合适的高度 */
  line-height: 32px !important;
  /* 匹配高度的行高 */
  vertical-align: middle;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 110px !important;
  /* 统一长度为110px */
}

/* 为下拉菜单标题添加边框和倾斜效果 */
:deep(.el-menu--horizontal > .el-submenu > .el-submenu__title) {
  box-sizing: border-box;
  position: relative;
  border: 1px solid #2CDFE8;
  border-radius: 4px;
  transform: skew(-20deg);
  transition: all 0.3s ease;
  background-color: transparent;
  overflow: hidden;
  margin: 0 3px;
  /* 适当的间距 */
  padding: 0 10px !important;
  /* 合适的内边距 */
  font-size: 14px !important;
  /* 适中的字号 */
  height: 32px !important;
  /* 合适的高度 */
  line-height: 32px !important;
  /* 匹配高度的行高 */
  vertical-align: middle;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 100px !important;
  /* 统一长度为110px */
  text-align: center;
  font-family: YouSheBiaoTiHei, YouSheBiaoTiHei !important;
  font-weight: 400;
}

:deep(.el-menu--horizontal > .el-submenu) {
  position: relative;
}

:deep(.el-menu--horizontal) {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  flex-wrap: nowrap;
}

/* 修正菜单项内文字，使其不跟随倾斜 */
:deep(.el-menu--horizontal > .el-menu-item) span,
:deep(.el-menu--horizontal > .el-submenu > .el-submenu__title) span {
  display: inline-block;
  transform: skew(20deg);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 修正菜单项内图标，使其不跟随倾斜 */
:deep(.el-menu--horizontal > .el-menu-item) i,
:deep(.el-menu--horizontal > .el-submenu > .el-submenu__title) i {
  display: inline-block;
  transform: skew(20deg);
}

/* 设置激活状态的背景颜色和边框 */
:deep(.el-menu--horizontal > .el-menu-item.is-active) {
  background-color: #0C5198 !important;
  /* border-color: #1A9ADB !important; */
  color: #fff !important;
}

:deep(.el-menu--horizontal > .el-submenu.is-active .el-submenu__title) {
  background-color: #0C5198 !important;
  /* border-color: #1A9ADB !important; */
  color: #fff !important;
}

/* 移除之前的底部蓝色条，因为现在使用背景色表示激活状态 */
:deep(.el-menu--horizontal > .el-menu-item.is-active)::after,
:deep(.el-menu--horizontal > .el-submenu.is-active .el-submenu__title)::after {
  display: none;
}

/* 保持hover状态不变色 */
:deep(.el-menu--horizontal > .el-menu-item:hover) {
  background-color: transparent !important;
  color: #fff !important;
}

:deep(.el-menu--horizontal > .el-submenu:hover > .el-submenu__title) {
  background-color: transparent !important;
  color: #fff !important;
}

:deep(.el-menu--horizontal>.el-submenu){
   
  margin: 0 15px;
  /* 左右各5px，总共10px间距 */
}

/* 下拉菜单 */
/* :deep(.el-menu--collapse .el-menu .el-submenu, .el-menu--popup){
  border: 1px solid #5EF4FF;
} */

:deep(.el-submenu__title i){
  font-size: 0px;
}

</style>
<style>
.el-menu--collapse .el-menu .el-submenu,
.el-menu--popup {
  min-width: 92px;
  background-color: #fff;
  color: #333;
  border: 1px solid rgba(94,244,255,0.5);
  text-align: center;
}

.el-menu--horizontal>.el-menu-item {
  margin: 0 20px;
  /* 左右各5px，总共10px间距 */
}


</style>